﻿// http://code.google.com/apis/gdata/reference.html
// http://lvchen.blogspot.com/feeds/comments/default?start-index=1&max-results=7
// http://lvchen.blogspot.com/feeds/posts/summary?published-min=2007-04-00&published-max=2007-04-31&max-results=90

// 修正 content 出現 <> 會造成顯示錯誤。


//----------- Define Global Variables, can be modified---------------
var rcPreSetting = {
blogDomain:'lvchen.blogspot.com',
showCount: 10,
noContent: ['原文已被刪除','<p>沒有留言可以顯示</p>','<p>我覺得你的網址打錯了喔！</p>'],
cachesize: 40,
showJumpButton:true,
showRCnoPost:false,
rcFoldImage:[
'http://lvchen.hostse.com/rc20/rc_0609_f.gif','留了言',
'http://lvchen.hostse.com/rc20/rc_0609_uf.gif','留言說:',
'<img src="http://lvchen.hostse.com/rc20/2-0.gif"/>&nbsp;載入中...',
'全部展開','全部隱藏'],
otherText:['跳至留言','我跳','上一頁','下一頁','您正在看留言 %range%，共有 %totalNum% 則留言','-'],
reply:['http://lvchen.hostse.com/rc20/external.png','直接去留言'],
rcAuthorLinkFormat:'<a href="%link%" title="%timestamp% &#65306; %short_content%">%author%</a>',
rcTitleLinkFormat: '<a href="%orgLink%">%g_szTitle%</a>',
createDisplayFormat:'%rcAuthorLinkFormat% 於 %rcTitleLinkFormat%%replyImg% %rcSay% &#12300;%content%&#12301; &nbsp;- %timestamp%',
today:'今天',
authorLink:true,
rcDateFormat: 1
};
// add %replyURL% and %replyImg%

//----------- Define Global Variables, should NOT be modified---------------

var rcSetting = {
g_szComments:[],
maxPostsNum:0,					// Max posts number
commentStartIndex : 1,			// find comment from 
commentTotalNum : 0,			// Total comments number
showAllFlag : false,			// Check if the showAll button clicke
outDate:0,
remainClose:0,
ready:false,
titleArr:[],
linkArr:[],
replyArr:[]
};
var rcFunction = {};		// The only Globa function...maybe

// ---------------------------------------------------------------
// 這個小程式可以用來尋找 id/class 裡的某個標籤
// id: 要被尋找的元素
// name: 要尋找的標籤名稱
// type: id/class
// ---------------------------------------------------------------
rcFunction.find = function(element,selector)	{
	function elArr(id,name,type) {
		switch (type)
		{
			case '#':
				if (id == '')
					return document.getElementById(name);
				var tags = id.getElementsByTagName('*');
				for (var i = 0 ; i < tags.length ; i++)
				{
					if (tags[i].id == name)
						return tags[i];
				}
				return undefined;
			case '.': // while getAttribute('class') && getElementsByClassName won't work
				var tagAll = (id=='') ? document.getElementsByTagName('*'): id.getElementsByTagName('*');
				var tags = new Array();
				//var reg = new RegExp(name);
				for (var i = 0 ; i < tagAll.length ; i++ )
				{
					var parse = tagAll[i].className.match(/^\S+|\S+|\S+$/g);
					if (parse != null)	{
						for (var j = 0; j < parse.length ; j++)	{
							if (name == parse[j])
								tags.push(tagAll[i]);
						}
					}
				}
				return (tags.length == 0) ? undefined : tags;
			default:
				var tags = (id == '') ? document.getElementsByTagName(type+name) : id.getElementsByTagName(type+name);
				return (tags.length == 0) ? undefined : tags;
		}
	}
	//var parse = selector.match(/^\S+|\S+|\S+$/g);
	return (element!='') ? elArr(element,selector.substr(1,(selector.length-1)),selector.substr(0,1)):elArr('',selector.substr(1,(selector.length-1)),selector.substr(0,1));
};

rcFunction.remove = function(element,selector)	{
	var tags = rcFunction.find(element, selector);
	if (tags)	{
		if (selector.substr(0,1) != '#')
			for (var i = 0 ; i < tags.length ; i)	{
				tags[0].parentNode.removeChild(tags[i]);
			}
		else
			tags.parentNode.removeChild(tags);
	}
};

rcFunction.html = function(elements, text)	{
	if (elements)	{
		for (var i = 0 ; i < elements.length ; i++)	{
			elements[i].innerHTML = text;
		}
	}
};
// ----------- Add header buttons---------------
rcFunction.addHeaderButton = function ()	{
	var eRC = document.getElementById('divrc');
	var cHeader = '<span id ="showAllButton" onclick = "rcFunction.showOrHideAll();">';
	cHeader += (rcSetting.showAllFlag) ? rcPreSetting.rcFoldImage[6]+'</span>' : rcPreSetting.rcFoldImage[5]+'</span>';
	if (rcPreSetting.showJumpButton)
		cHeader += '<form style= "display:inline;margin-left:1em" onsumbit="return false" name="jumpForm" action=""><span id="jumpSet">'+rcPreSetting.otherText[0]+'&nbsp;&nbsp;<input style="text-align:center; width:2em" type="text" name="itemJump" value="1"  onkeypress="if(event.keyCode==13||event.which == 13) {rcFunction.changePage(0,this.value); return false;}"/>&nbsp;<input id="jumpButton" type="button" value="'+rcPreSetting.otherText[1]+'" onclick="rcFunction.changePage(0,itemJump.value);"/></span></form>';
	var eHeader = document.createElement('div');
	eHeader.id = 'headerButton';
	eHeader.style.display = 'none'; // Hide Header until everything loaded
	eHeader.innerHTML = cHeader;
	eRC.appendChild(eHeader);
	var showAllButton = rcFunction.find(eRC,'#showAllButton');
	showAllButton.onmouseover = function(){this.style.cursor = 'pointer';}; // change cursor to pointer
	showAllButton.onmouseout = function(){this.style.cursor = 'default';};  // change cursor back to default
};
//--------------------------------------------------------------
// Fetch comment JSON feed.
// Several variables conflicted are also solved here.
//--------------------------------------------------------------
rcFunction.commentJSONfeed = function (json)	{ 
	if (!rcSetting.ready)
		rcSetting.ready = true; // The script is successfully loaded.
	if (json.feed.entry!=undefined)	{
		rcSetting.g_szComments = json.feed.entry;
		if (rcSetting.commentTotalNum == 0)
			rcSetting.commentTotalNum = json.feed.openSearch$totalResults.$t*1;   // Retrive total number of comments
		if (rcPreSetting.showCount > rcSetting.commentTotalNum)
			rcPreSetting.showCount = rcSetting.commentTotalNum;
		rcFunction.fetchPostsTitle(1,'');
	}
	else
		document.getElementById('divrc').innerHTML(rcPreSetting.noContent[1]);
};

//--------------------------------------------------------------
//		Get the feed of comments from the Blogger.
//--------------------------------------------------------------
rcFunction.fetchComments = function(Index,increment)	{
	document.getElementById('jumpButton').disabled = 'disabled'; // Regain header control
	rcFunction.remove('','#jsonComments');
	y_script = document.createElement('script');
	var callbacksrc = 'http://' + rcPreSetting.blogDomain + '/feeds/comments/default?alt=json-in-script&callback=rcFunction.commentJSONfeed&max-results=' + increment + '&start-index='+ Index;
	y_script.src = callbacksrc;
	y_script.id = 'jsonCommnets';
	y_script.type = 'text/javascript';
	try { //I trt
		document.documentElement.firstChild.appendChild(y_script); // Load the script and get data from Google Blogger
	}
	catch(e) {}
	// if anything goes wrong, wait for 10 more seconds.
	setTimeout(function (){
		if (!rcSetting.ready) {
			document.getElementById('divrc').innerHTML = rcPreSetting.noContent[2];
		}
	},10000);
};

// ---------------------------------------------------------------
// ---------------------------------------------------------------
rcFunction.fetchPostsTitle = function(Index,source)	{
	rcFunction.remove('','#jsonPosts');
	if (rcSetting.linkArr.length > 0 && source == '')
	{
		rcFunction.titleJSONfeed('');
	}
	else
	{
		var y_script = document.createElement('script');
		if (source !='')
			callbacksrc = source + '?&alt=json-in-script&callback=rcFunction.findLossTitles';
		else		
			callbacksrc = 'http://' + rcPreSetting.blogDomain +	'/feeds/posts/summary?max-results='+ rcPreSetting.cachesize + '&start-index=' + Index + '&alt=json-in-script&callback=rcFunction.titleJSONfeed';
		y_script.src = callbacksrc;
		y_script.id = 'jsonPosts';
		y_script.type = 'text/javascript';
		document.documentElement.firstChild.appendChild(y_script);
	}
};

rcFunction.findTitle = function(orgLink)	{
	var loop = rcPreSetting.cachesize; 				// set up looping time, default is 30, which means we check only 30 title every time.
	for (var j = 0 ; j < loop ; j++)				// This is main loop to chekc if the title of the link exists.
	{
		if (rcSetting.linkArr[j] == orgLink)
			break;
	}
	if (j != loop)
		return j;
	else
		return -1;
	
};
// ---------------------------------------------------------------
// ----------- converts Month --------------
// ---------------------------------------------------------------
rcFunction.monthConvert = function(monthIndex)	{
	var monthName=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
	return monthName[(parseInt(monthIndex,10)-1)];
};
// ---------------------------------------------------------------
//----------- check dates Get Today's Date---------------
// ---------------------------------------------------------------
rcFunction.checkTodayDate = function(dateString)	{
	var timeStr = new Date();
	var rcDateStr = new Date(parseInt(dateString.substr(0,4),10),parseInt(dateString.substr(5,2),10)-1,parseInt(dateString.substr(8,2),10));
	//alert, I am not sure this method is working, Better test before try. 04/04/2008
	//rcDateStr.setFullYear(parseInt(dateString.substr(0,4),10),parseInt(dateString.substr(5,2),10)-1,parseInt(dateString.substr(8,2),10));
	if (rcDateStr.getYear() == timeStr.getYear())
	{
		if (rcDateStr.getMonth() == timeStr.getMonth())
		{
			if (rcDateStr.getDate() == timeStr.getDate())
				return true;
			else
				return false;
		}
		else
			return false;
	}
	else
		return false;
};

rcFunction.createFormat = function (rcInfo)	{
	//rcAuthorLinkFormat:'<a href="%link%" title="%timestamp% &#65306; %short_content%">%author%</a>'
	//rcTitleLinkFormat: '<a href="%orgLink%">%g_szTitle%</a>'
	//createDisplayFormat:'%rcAuthorLinkFormat% 於 %rcTitleLinkFormat%%replyImg% %rcSay% &#12300;%content%&#12301; &nbsp;- %timestamp%'
	// I will need: authorLink, author, orgLink, replyURL,content, timestamp, title
	var i;
	rcInfo.sContent = rcInfo.content.replace(/<.*?>/g,''); // Remove HTML tags
	if (rcInfo.sContent.length > 40)		rcInfo.sContent = rcInfo.sContent.substr(0,40)+'...';
	rcInfo.sContent = rcInfo.sContent.replace(/"/gim,"&quot;"); // fix short_content masses up author display
	var parseString = rcPreSetting.createDisplayFormat;
	var displayFormat = document.createElement('li');
	parseString = parseString.replace(/%rcAuthorLinkFormat%/g,'<span class = "rcAuthor"></span>');
	parseString = parseString.replace(/%rcTitleLinkFormat%/g,'<span class = "rcPostTitle"></span>');
	parseString = parseString.replace(/%replyImg%/g,'<span class="rcReply"></span>');
	parseString = parseString.replace(/%timestamp%/g,'<span class="rcTimeStamp"></span>');
	parseString = parseString.replace(/%rcSay%/g,'<span class="rcsay"></span>');
	parseString = parseString.replace(/\s*(\S*)%content%(\S*)\s*/g, '<span class="comcontent">$1<span class="iContent"></span>$2</span>');
	displayFormat.innerHTML = parseString;
	// putting authorFormat
	parseString = rcPreSetting.rcAuthorLinkFormat;
	parseString = parseString.replace(/%link%/g,rcInfo.authorLink);
	parseString = parseString.replace(/%author%/g, rcInfo.author);
	parseString = parseString.replace(/%replyURL%/g, rcInfo.replyURL);
	parseString = parseString.replace(/%short_content%/g, rcInfo.sContent);
	parseString = parseString.replace(/%timestamp%/g,rcInfo.timestamp);
	rcFunction.html(rcFunction.find(displayFormat,'.rcAuthor'), parseString);
	// putting titleFormat
	parseString = rcPreSetting.rcTitleLinkFormat;
	parseString = parseString.replace(/%orgLink%/g, rcInfo.orgLink);
	parseString = parseString.replace(/%g_szTitle%/g, rcInfo.title);
	parseString = parseString.replace(/%replyURL%/g, rcInfo.replyURL);
	parseString = parseString.replace(/%short_content%/g, rcInfo.sContent);
	parseString = parseString.replace(/%timestamp%/g, rcInfo.timestamp);
	rcFunction.html(rcFunction.find(displayFormat,'.rcPostTitle'), parseString);
	rcFunction.html(rcFunction.find(displayFormat,'.rcReply'), (rcPreSetting.reply[0]!='') ? '<a href="'+ rcInfo.replyURL +'" target="_blank"><img style = "background:none ;border-style: none" src="'+ rcPreSetting.reply[0] +'" alt="'+ rcPreSetting.reply[1] +'" /></a>' : '<a href="'+ rcInfo.replyURL +'">'+ rcPreSetting.reply[1] +'</a>');
	rcFunction.html(rcFunction.find(displayFormat,'.rcsay'), (rcSetting.showAllFlag) ? rcPreSetting.rcFoldImage[3] : rcPreSetting.rcFoldImage[1]);
	rcFunction.html(rcFunction.find(displayFormat,'.rcTimeStamp'), rcInfo.timestamp);
	var theNode  = rcFunction.find(displayFormat,'.iContent');
	if (theNode)	{// folding feature is used when full content exists.
		displayFormat.style.listStyle = 'none';
		displayFormat.style.background = 'none';
		var lFold = document.createElement('span');
		lFold.className = 'rcfold';
		lFold.innerHTML = '&nbsp;&nbsp;&nbsp;';
		lFold.style.background = (rcSetting.showAllFlag) ? 'url('+rcPreSetting.rcFoldImage[2]+') center no-repeat' : 'url('+rcPreSetting.rcFoldImage[0]+') center no-repeat';
		displayFormat.insertBefore(lFold,displayFormat.firstChild);
		for (i = 0; i<theNode.length ; i++)	{
			theNode[i].innerHTML = rcInfo.content;
			if (!rcSetting.showAllFlag)
				rcFunction.find(displayFormat,'.comcontent')[i].style.display = 'none';
		}
	}
	else
		rcFunction.remove(rcFunction.find('','#divrc'), '#showAllButton');
	return displayFormat;
};

// ---------------------------------------------------------------
//----------- Fetch posts JSON feed, several variables that is comments related are determine here ---------------
//----------- Look for matched titles and show comments ---------------
// ---------------------------------------------------------------
rcFunction.titleJSONfeed = function (posts)	{	
	var rcInfo = {
		authorLink: '',
		orgLink: '',
		author: '',
		replyURL: '',
		title: '',
		content: '',
		timestamp: ''
	};
	// initial variables
	var eRC = document.getElementById('divrc');
	var cBody = document.createElement('ul');
	cBody.id = 'feedItemListDisplay';
	cBody.style.display = 'none';
	var checkLink = '';
	var checkTitle = '';
	var reaplyImg,replyURL,findIdx,g_szTitle,linkidx;
	// Cache title and its URL
	if (rcPreSetting.createDisplayFormat.indexOf('%rcTitleLinkFormat%') != -1) //cache if we need to find a title
	{
		if (posts != '' && posts.feed.entry != undefined)
		{
			var entries = posts.feed.entry;
			if (rcSetting.maxPostsNum == 0)
				rcSetting.maxPostsNum = posts.feed.openSearch$totalResults.$t*1;
			if (entries.length*1 < rcPreSetting.cachesize) // if only a few posts, correct the cachesize
				rcPreSetting.cachesize = entries.length*1;
			for (var i = 0 ; i < rcPreSetting.cachesize ; i++)
			{
				var titleLinkIdx = replyLinkIdx ='';
				var j = 0;
				while (j < entries[i].link.length)
				{
					if (entries[i].link[j].rel == "alternate")
						titleLinkIdx = j;
					else if (entries[i].link[j].rel == "replies" && entries[i].link[j].type == 'text/html')
						replyLinkIdx = j;
					if (titleLinkIdx!='' && replyLinkIdx!='')
						break;
					j++;
				}
				rcSetting.linkArr[i] = entries[i].link[titleLinkIdx].href;
				rcSetting.titleArr[i] = entries[i].title.$t;
				if (replyLinkIdx!='')
					rcSetting.replyArr[i] = entries[i].link[replyLinkIdx].href;
				else
					rcSetting.replyArr[i] = '';
			}
		}		
	}
	//----------- Main loop to create a list of comments  -------------------------------------------------------
	//----------- Post URLs are located and compared for getting the name of its title	 ---------------
	for (i=0; i < rcSetting.g_szComments.length*1; i++)
	{
		var comment = rcSetting.g_szComments[i]; // Extract comments from JSON
		j = 0;
		while (j<comment.link.length && comment.link[j].rel != "alternate")
			j++;
		linkidx = j;
		rcInfo.authorLink = (rcPreSetting.authorLink && comment.author[0].uri != undefined) ? comment.author[0].uri.$t : comment.link[linkidx].href;
		//if (rcInfo.authorLink.indexOf('#') > 0)
		rcInfo.orgLink = comment.link[linkidx].href.replace(/(^.+)\?.*$/,'$1'); // Link URL of the Post
		if (rcPreSetting.createDisplayFormat.indexOf('%rcTitleLinkFormat%') != -1)
		{
			if (rcInfo.orgLink != checkLink)  // if the previous comment is from the same post, then we don't have to look for the title of the post
			{
				findIdx = rcFunction.findTitle(rcInfo.orgLink);
				if (findIdx == -1)
				{
					rcInfo.title = (comment['thr$in-reply-to']!=undefined) ? '<span class="noTitleMessage">' + comment["thr$in-reply-to"].source + '</span>' : '<span class="postDeleted"></span>'
				}
				else
				{
					rcInfo.title = rcSetting.titleArr[findIdx];
					rcInfo.replyURL = rcSetting.replyArr[findIdx];
				}
				checkTitle = rcInfo.title;
				checkLink  = rcInfo.orgLink;
			}
			else
				rcInfo.title = checkTitle;
		}	
		if (comment.content== undefined) // This will check wheather full or short comment feed
		{
			rcInfo.content = comment.summary.$t;
			rcInfo.content = rcInfo.content.replace(/\u003c/g,'<'); // fix < 04/28/2008
			rcInfo.content = rcInfo.content.replace(/\u003e/g,'>'); // fix > 04/28/2008
		}			
		else
			rcInfo.content = comment.content.$t;   // The complete content of a comment.
		//content = content.replace(/\$/g,'&#36;'); // fix $1 and $2 being replaced. 9/6/2007
		rcInfo.author = comment.author[0].name.$t;  // Author's Name
		//----------- Select Date Format and do some necessary modification---------------
		if (rcPreSetting.rcDateFormat == 1)
		{
			rcInfo.timestamp = comment.published.$t.substr(0,10); // Determine date and time.
			if (rcFunction.checkTodayDate(rcInfo.timestamp))
				rcInfo.timestamp = rcPreSetting.today + ' ' + comment.published.$t.substr(11,5);
		}
		else if (rcPreSetting.rcDateFormat == 2)
			rcInfo.timestamp=rcFunction.monthConvert(comment.published.$t.substr(5,2))+'&nbsp;'+comment.published.$t.substr(8,2);
		cBody.appendChild(rcFunction.createFormat(rcInfo));
	}
	eRC.appendChild(cBody);
	// Some necessary operations to match custom format
	var cList = cBody.getElementsByTagName('li');
	for (i = 0 ; i < cList.length ; i++)	{
		if (rcFunction.find(cList[i], '.postDeleted'))	{
			if (rcPreSetting.showRCnoPost)	{
				rcFunction.html(rcFunction.find(cList[i], '.rcPostTitle'),rcPreSetting.noContent[0]);
				var theNodes = rcFunction.find(cList[i], '.rcAuthor');
				for (var j = 0 ; j < theNodes.length ; j++)	{
					theNodes[j].innerHTML = theNodes[j].innerHTML.replace(/<(?:.|\s)*?>/g,'');
				}
			}
			else	{
				cBody.removeChild(cList[i]);
				i--;
			}
		}
		else if (rcFunction.find(cList[i], '.noTitleMessage'))
			rcSetting.outDate++;
	}
	if (rcSetting.outDate == 0)	{
		if (cList.length == 0)
			cBody.innerHTML = rcPreSetting.noContent[1];
		rcFunction.addFooterButton();
	}
	else
		rcFunction.titleReCheck(); // go to titleCheck to check if any title misses.	
};

rcFunction.addFooterButton = function () {//This function is only used in titleCheck(), so I make it an inner function for easy management
	var text = rcPreSetting.otherText;
	var index = rcSetting.commentStartIndex; // Current index #
	var tnum = rcSetting.commentTotalNum; // Total number of comments we have
	var g_show = rcPreSetting.showCount; // How many comments we show for one page
	if (index + g_show > tnum)
		g_show = tnum - index + 1;
	var commentInfo =text[4].replace(/%range%/,index + text[5] + (index+g_show-1));
	commentInfo = commentInfo.replace(/%totalNum%/,tnum);		
	var footer = document.createElement('div');
	footer.id = 'showfooterButton';
	footer.style.display = 'none';
	if (index == 1)
	{
		if (tnum != g_show)
			commentInfo += '<div class ="footerMsg"><a href="javascript:void(0);" onclick="rcFunction.changePage(1,0);">'+text[3]+'</a></div>';
	}
	else if (g_show + index > tnum)
	{
		commentInfo += '<div class ="footerMsg"><a href="javascript:void(0);" onclick="rcFunction.changePage(-1,0);">'+text[2]+'</a></div>';
	}
	else 
	{
		commentInfo += '<div class ="footerMsg"><a href="javascript:void(0);" onclick="rcFunction.changePage(-1,0);">'+text[2]+'</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:void(0);" onclick="rcFunction.changePage(1,0);">'+text[3]+'</a></div>';
	}
	footer.innerHTML = commentInfo;
	// Now load the footer
	var eRC = document.getElementById('divrc');
	eRC.appendChild(footer);
	rcFunction.finalActions();
};

rcFunction.titleReCheck = function()	{
	var source = rcFunction.find(document.getElementById('divrc'), '#feedItemListDisplay');
	source = rcFunction.find(source, '.noTitleMessage');
	source = source[0].innerHTML;
	rcFunction.fetchPostsTitle(1,source);
};

rcFunction.findLossTitles = function (posts)	{
		var title = posts.entry.title.$t;
		var link = posts.entry.link;
		for (var i = 0 ; i < link.length ; i++)
		{
			if (link[i].rel == 'alternate')
				var titleLink = link[i].href;
			else if (link[i].rel == 'replies' && link[i].type == 'text/html')
				var replyLink = link[i].href;
			else if (link[i].rel == 'self')
				var sourceLink = link[i].href;
		}
		var cBody = rcFunction.find(document.getElementById('divrc'), '#feedItemListDisplay');
		var cList = cBody.getElementsByTagName('li');
		for (i = 0 ; i < cList.length ; i++) {
			var cNoTitle = rcFunction.find(cList[i], '.noTitleMessage');
			if (cNoTitle)	{
				if (cNoTitle[0].innerHTML == sourceLink)	{
					for (var j = 0 ; j < cNoTitle.length ; j++)	{
						cNoTitle[j].parentNode.innerHTML = title;
						var theNodes = rcFunction.find(cList[i], '.rcReply');
						for (var k = 0 ; k < theNodes.length ; k++) {
							theNodes[k].getElementsByTagName('a')[0].setAttribute('href',replyLink);
						}									
					}
				rcSetting.outDate--;
				}
			}
		}

	if (rcSetting.outDate != 0)
		rcFunction.titleReCheck();
	else	{
		rcFunction.addFooterButton();
	}
 };

//--------------------------------------------------------------
//--		 Some actions need to be taken care 			  --
//--	 1. Hide detailed content of comments 				  --
//--     2. Add mouseover event to each comment         	  --
//--     3. Add mouseout event to each comment                --
//--     4. Add click event handler to each comment 		  --
//--	 5. Click handler will take care the click event when --
//--		switch on/off the detail content.                 --
//-- 												7/1/09	  --
//--------------------------------------------------------------
rcFunction.finalActions = function ()	{
	var eRC = document.getElementById('divrc');
	var cList = rcFunction.find(rcFunction.find(eRC,'#feedItemListDisplay'),'li');
	var showAllButton = rcFunction.find(eRC,'#showAllButton');
	var lComcontent = rcFunction.find(eRC, '.comcontent');
	var lFold = rcFunction.find(eRC, '.rcfold');
	var lSay = rcFunction.find(eRC, '.rcsay');

	rcSetting.remainClose = (rcSetting.showAllFlag)	? rcPreSetting.showCount : 0;
	// The inner function for click event handler
	function fClick(idx){
		if (lComcontent[idx].style.display == 'none')	{ // Check if the comment detail is shown
			lFold[idx].style.background = 'url(' + rcPreSetting.rcFoldImage[2] + ') center no-repeat';
			lSay[idx].innerHTML = rcPreSetting.rcFoldImage[3];
			lComcontent[idx].style.display = 'inline';
			rcSetting.remainClose++;
		}
		else {
			lFold[idx].style.background = 'url(' + rcPreSetting.rcFoldImage[0] + ') center no-repeat';
			lSay[idx].innerHTML = rcPreSetting.rcFoldImage[1];
			lComcontent[idx].style.display = 'none';
			rcSetting.remainClose--;
		}
		
		if (rcSetting.remainClose == 0)	{ // if detailed content of the all comments are shown, change the text of the showallbutton
			showAllButton.innerHTML = rcPreSetting.rcFoldImage[5];
			rcSetting.showAllFlag = false;
		}
		else if (rcSetting.remainClose == rcPreSetting.showCount)	{
			showAllButton.innerHTML = rcPreSetting.rcFoldImage[6];
			rcSetting.showAllFlag = true;
		}
		//alert(rcSetting.remainClose);
	};
	// Attach click event handler to the switch, IE is quite annoying here but I got a pretty good solution.
	document.getElementById('headerButton').removeAttribute('style'); // Get the header show now.
	document.getElementById('feedItemListDisplay').removeAttribute('style'); 
	document.getElementById('showfooterButton').removeAttribute('style');
	rcFunction.remove(document.getElementById('divrc'), '#loadingMsg');
	document.getElementById('jumpButton').removeAttribute('disabled'); // Regain header control	
	if (cList.length> 0)	{
		if (lFold)	{
			for (var i = 0 ; i < lFold.length ; i++)	{
					lFold[i].liNum = i; // add a own property for li index, this way, we know which <li> we deal with, works in FF
					lFold[i].onmouseover = function(){this.style.cursor = 'pointer';}; // change cursor to pointer
					lFold[i].onmouseout = function(){this.style.cursor = 'default';};  // change cursor back to default 
					if (typeof window.addEventListener != 'undefined') //add event handler, only event handler can process in the inner function
						lFold[i].addEventListener('click',function(){fClick(this.liNum);},false);
					else	// for IE http://www.howtocreate.co.uk/tutorials/javascript/domevents
						lFold[i].attachEvent('onclick',function(e){
							var theTarget = e.target ? e.target : e.srcElement; 
							if( theTarget && ( theTarget.nodeType == 3 ) ) { theTarget = theTarget.parentNode;}
							fClick(theTarget.liNum);});
			}
		}
	}
};

// ----------- Handler for showing  or hiding all comment -----------
// ----------- Dynamic onclick does not work, so I merge two function into one. it seems working and running better ! 10/17 -----------
rcFunction.showOrHideAll = function()	{
	var eRC = document.getElementById('divrc');
	var cList = eRC.getElementsByTagName('li');
	var lComcontent = rcFunction.find(eRC,'.comcontent');
	var lFold = rcFunction.find(eRC, '.rcfold');
	var lSay = rcFunction.find(eRC, '.rcsay');
	var showAllButton = rcFunction.find(eRC,'#showAllButton');
	if (rcSetting.showAllFlag)
	{
		for (var i = 0 ; i < cList.length ; i++)	{
			lComcontent[i].style.display = 'none';
			lFold[i].style.background = 'url(' + rcPreSetting.rcFoldImage[0] + ') center no-repeat';
			lSay[i].innerHTML = rcPreSetting.rcFoldImage[1];
		}
		showAllButton.innerHTML = rcPreSetting.rcFoldImage[5];
		rcSetting.showAllFlag = false;		
	}
	else
	{
		for (var i = 0 ; i < cList.length ; i++)	{
			lComcontent[i].style.display = 'inline';
			lFold[i].style.background = 'url(' + rcPreSetting.rcFoldImage[2] + ') center no-repeat';
			lSay[i].innerHTML = rcPreSetting.rcFoldImage[3];
		}
		showAllButton.innerHTML = rcPreSetting.rcFoldImage[6];
		rcSetting.showAllFlag = true;
	}	
};

//--------------------------------------------------------------
//----------- ChangePage, backward, forward, or jump ---------------
//----------- Direction = -1, backward               ---------------
//----------- Direction =  0, jump by index          ---------------
//----------- Direction =  1,  forward               ---------------
//----------- Direction =  2,  jump by date          ---------------
//----------- indexIwant is index I want             ---------------
//--------------------------------------------------------------
rcFunction.changePage = function(direction,indexIwant)	{
	var jump = true;
	if (direction == 1) // Next page
		rcSetting.commentStartIndex += rcPreSetting.showCount;
	else if (direction == -1) // previsous page
		rcSetting.commentStartIndex -= rcPreSetting.showCount;
	else
	{//rcFunction.gotoIndexIwant = function (indexIwant)
		if (indexIwant > rcSetting.commentTotalNum)
			indexIwant = rcSetting.commentTotalNum;
		else if (indexIwant < 1)
			indexIwant = 1;
		var pageNumber = Math.ceil(indexIwant/rcPreSetting.showCount);
		if (pageNumber == Math.ceil(rcSetting.commentStartIndex/rcPreSetting.showCount))
			jump = false;
		else
			rcSetting.commentStartIndex = (pageNumber-1)*rcPreSetting.showCount + 1;	
	}
	if (jump)// 同一頁不跳， 不同頁我跳
	{
		var eRC = document.getElementById('divrc');
		rcFunction.remove(eRC, '#feedItemListDisplay');
		rcFunction.remove(eRC, '#showfooterButton');
		theNode = document.createElement('div');
		theNode.id = 'loadingMsg';
		theNode.innerHTML = rcPreSetting.rcFoldImage[4];
		eRC.appendChild(theNode);
		if (rcSetting.commentStartIndex + rcPreSetting.showCount > rcSetting.commentTotalNum)
			rcFunction.fetchComments(rcSetting.commentStartIndex, rcSetting.commentTotalNum - rcSetting.commentStartIndex + 1);
		else
			rcFunction.fetchComments(rcSetting.commentStartIndex, rcPreSetting.showCount);
	}
};

document.getElementById('divrc').innerHTML = '<div id="loadingMsg">' + rcPreSetting.rcFoldImage[4] + '</div>';
rcFunction.addHeaderButton();
